# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: jhkim

import glob
import json
import pandas
import functools


class ProductInfoHolder(object):
  def __init__(self):
    files1 = list(glob.glob('data/coin2/product_info/*.json'))
    files2 = list(glob.glob('../data/coin2/product_info/*.json'))
    dfs = []
    for product_info_file in files1 + files2:
      pi_obj = json.load(open(product_info_file))
      each_df = pandas.DataFrame(pi_obj['product_infos'])
      each_df['mea'] = pi_obj['mea']
      dfs.append(each_df)
    df = pandas.concat(dfs, axis=0, sort=False)
    df['exchange'] = df['mea'].str.split('.').str[1]
    self.df_pi = df

  @staticmethod
  def relative_norm(product):
    ret = (
        product.subscription_symbol
        if hasattr(product, 'subscription_symbol')
        else product.symbol)
    ret = (
        ret.replace('.CURRENT_QUARTER', '.QUARTER')
          .replace('.CURRENT_WEEK', '.WEEK')
          .replace('.THIS_WEEK', '.WEEK'))
    return ret

  @functools.lru_cache()
  def get_product_info(self, product):
    relnorm = ProductInfoHolder.relative_norm(product)
    # coin1 bchn -> coin2 bchabc
    # coin1 bchabc -> coin2 bcha
    relnorm = (
        relnorm
        .replace("BCHN-", "BCHABC-"))
    cond = (
        (self.df_pi['exchange'] == product.exchange) &
        (self.df_pi['symbol'] == relnorm))
    if cond.sum() == 0:
      return None
    else:
      ret = self.df_pi.loc[cond]
    return ret.iloc[0].to_dict()


if __name__ == '__main__':
  ph = ProductInfoHolder()
  dbg = ph.df_pi
  print(dbg.loc[dbg['symbol'].str.find('BCH') >= 0][[
      'mea', 'base', 'symbol', 'native_symbol', 'contract_value']].to_string())
  print(dbg.loc[dbg['symbol'].str.find('BTC-') >= 0][[
      'mea', 'base', 'symbol', 'native_symbol', 'contract_value']].to_string())
